package com.xjh.controller;

import com.alibaba.fastjson2.JSON;
import com.xjh.bo.TestValidBO;
import com.xjh.config.QyVxConfig;
import com.xjh.utils.resultutils.ResponseObj;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;

import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;

import me.chanjar.weixin.cp.bean.WxCpUser;

import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

/**
 * @author XuJianHua
 * @date 2022-08-23 16:19:16
 * @description 测试对接企业微信（主要是wxjava-cp）
 */
@RestController
@RequestMapping("/api/qy")
@Slf4j
public class TestQyVxController {


    public static final String CORPID = "wx7e4271dc09a7a1fd";
    public static final Integer AGENTID = 3010040;
    public static final String CORPSECRET = "0uq2oPZP7daKID_SDXTqLbPhKUZAdz2NSMQuO64jEYw";

    public static final String TEMPLATE_ID = "1970325006023083_1688851476324306_583259002_1524556136";
    @GetMapping("/test")
    public ResponseObj test()  {

        ResponseObj responseObj = new ResponseObj();
        WxCpService wxCpService = QyVxConfig.getWxCpService();
        return  responseObj.ok();
    }

// 获取模板测试
    @GetMapping("/testValid111")
    public ResponseObj queryAlld() throws WxErrorException {
        WxCpService wxCpService = QyVxConfig.getWxCpService();
        System.out.println("accessToken===" + wxCpService.getAccessToken());
/*
errcode
errmsg
template_names
  -text
  -lang
template_content
  -controls(list)
    -property(map)
      -control
      -id(字段id)
      -title(list)
        -text(入账部门)
        -lang
    -config(map与porperty同级)
      -selector
      -type
      -options(list)
        -key(选项key)
        -value
          -text(总经办)
          -lang
* * * * * * */
        // 根据参数获取模板
        HashMap<String, String> templateIdMap = new HashMap<>();
        templateIdMap.put("template_id", TEMPLATE_ID);
        // 请求参数转json
        String s = JSON.toJSONString(templateIdMap);
        String templateInfoString = wxCpService.post("https://qyapi.weixin.qq.com/cgi-bin/oa/gettemplatedetail", s);
        log.info("模板响应字符串===" + templateInfoString);
        // 将字符串转为map并取出数据
        Map<String, Object> templateMap = JSON.parseObject(templateInfoString, Map.class);
        log.info("errcode===" + templateMap.get("errcode"));
        log.info("errmsg===" + templateMap.get("errmsg"));
        log.info("template_names===" + templateMap.get("template_names"));
        log.info("template_content===" + templateMap.get("template_content"));
        Map<String, Object> templateContent = (Map<String, Object>) templateMap.get("template_content");
        // 里面用object，因为id是个字符串，但是title是个jsonArray,不能转成字符串
        List<Map<String, Map<String, Object>>> controls = JSON.parseObject(templateContent.get("controls").toString(), List.class);
        log.info("controls===" + templateContent.get("controls"));
        log.info("controls22===" + controls);
        List< Map<String, Object> > datalist = new ArrayList<>();
        controls.forEach(e -> {
            Map<String, Object> dataMap = new HashMap();
            System.out.println(e.get("property").get("id"));
            dataMap.put("id", e.get("property").get("id").toString());
            System.out.println(e.get("property").get("title"));
            List<Map<String, String>> title = JSON.parseObject(e.get("property").get("title").toString(), List.class);
            dataMap.put("title", title.get(0).get("text"));
            // 如果是选择器类型则需要获取选项
            if (e.get("property").get("control").equals("Selector")) {
                System.out.println(e.get("config"));
               Map<String,Object> selector =  JSON.parseObject(e.get("config").get("selector").toString(),Map.class);
                List<Map<String, Object>> options = JSON.parseObject(selector.get("options").toString(), List.class);
                List< Map<String, String> > optionList = new ArrayList<>();
                options.forEach(o -> {
                    Map<String, String> optionsMap = new HashMap<>();
                    optionsMap.put("key", o.get("key").toString());
                    List<Map<String, String>> values = JSON.parseObject(o.get("value").toString(), List.class);
                    optionsMap.put("values", values.get(0).get("text"));
                    optionList.add(optionsMap);
                    dataMap.put("optionList", optionList);
                });

            }
            datalist.add(dataMap);
        });


        ResponseObj responseObj = new ResponseObj();
        return responseObj.ok(datalist);

    }

//    @GetMapping("/testValid")
//    public ResponseObj queryAll() throws WxErrorException {
//
//
//        System.out.println("=====================================push()=============================");
////        WxCpDefaultConfigImpl config = new WxCpDefaultConfigImpl();
//// 老版本 获取token的方法
//        WxCpInMemoryConfigStorage config = new WxCpInMemoryConfigStorage();
//        config.setCorpId(CORPID);      // 设置微信企业号的appid
//        config.setCorpSecret(CORPSECRET);  // 设置微信企业号的app corpSecret
//        config.setAgentId(AGENTID);     // 设置微信企业号应用ID
//        // config.setToken(token);       // 设置微信企业号应用的token
//
//
//        WxCpServiceImpl wxCpService = new WxCpServiceImpl();
//        wxCpService.setWxCpConfigStorage(config);
//
////        System.out.println(user + "===" + content);
////        WxCpMessage message = WxCpMessage.TEXT().agentId(AGENTID).toUser(user).content(content).build();
////        wxCpService.messageSend(message);
////        WxCpUser usercp = wxCpService.getUserService().getById(user);
//        System.out.println("accessToken===" + wxCpService.getAccessToken());
////        System.out.println("accessToken===" + usercp.getName() + "===" + usercp.getMobile());
//
//
//        ResponseObj responseObj = new ResponseObj();
//        return responseObj.ok("牛啊");
//
//
//
//    }

    @GetMapping("/testXmlData")
    public ResponseObj queryAllee() throws WxErrorException {


        String xmlData = "<xml>\n" +
                "  <ToUserName><![CDATA[ww1cSD21f1e9c0caaa]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[sys]]></FromUserName>\n" +
                "  <CreateTime>1571732272</CreateTime>\n" +
                "  <MsgType><![CDATA[event]]></MsgType>\n" +
                "  <Event><![CDATA[sys_approval_change]]></Event>\n" +
                "  <AgentID>3010040</AgentID>\n" +
                "  <ApprovalInfo>\n" +
                "    <SpNo>201910220003</SpNo>\n" +
                "    <SpName><![CDATA[示例模板]]></SpName>\n" +
                "    <SpStatus>1</SpStatus>\n" +
                "    <TemplateId><![CDATA[3TkaH5KFbrG9heEQWLJjhgpFwmqAFB4dLEnapaB7aaa]]></TemplateId>\n" +
                "    <ApplyTime>1571728713</ApplyTime>\n" +
                "    <Applyer>\n" +
                "      <UserId><![CDATA[WuJunJie]]></UserId>\n" +
                "      <Party><![CDATA[1]]></Party>\n" +
                "    </Applyer>\n" +
                "    <SpRecord>\n" +
                "      <SpStatus>1</SpStatus>\n" +
                "      <ApproverAttr>2</ApproverAttr>\n" +
                "      <Details>\n" +
                "        <Approver>\n" +
                "          <UserId><![CDATA[WangXiaoMing]]></UserId>\n" +
                "        </Approver>\n" +
                "        <Speech><![CDATA[]]></Speech>\n" +
                "        <SpStatus>1</SpStatus>\n" +
                "        <SpTime>0</SpTime>\n" +
                "      </Details>\n" +
                "      <Details>\n" +
                "        <Approver>\n" +
                "          <UserId><![CDATA[XiaoGangHuang]]></UserId>\n" +
                "        </Approver>\n" +
                "        <Speech><![CDATA[]]></Speech>\n" +
                "        <SpStatus>1</SpStatus>\n" +
                "        <SpTime>0</SpTime>\n" +
                "      </Details>\n" +
                "    </SpRecord>\n" +
                "    <SpRecord>\n" +
                "      <SpStatus>1</SpStatus>\n" +
                "      <ApproverAttr>1</ApproverAttr>\n" +
                "      <Details>\n" +
                "        <Approver>\n" +
                "          <UserId><![CDATA[XiaoHongLiu]]></UserId>\n" +
                "        </Approver>\n" +
                "        <Speech><![CDATA[]]></Speech>\n" +
                "        <SpStatus>1</SpStatus>\n" +
                "        <SpTime>0</SpTime>\n" +
                "      </Details>\n" +
                "    </SpRecord>\n" +
                "    <Notifyer>\n" +
                "      <UserId><![CDATA[ChengLiang]]></UserId>\n" +
                "    </Notifyer>\n" +
                "    <Comments>\n" +
                "      <CommentUserInfo>\n" +
                "        <UserId><![CDATA[LiuZhi]]></UserId>\n" +
                "      </CommentUserInfo>\n" +
                "      <CommentTime>1571732272</CommentTime>\n" +
                "      <CommentContent><![CDATA[这是一个备注]]></CommentContent>\n" +
                "      <CommentId><![CDATA[6750538708562308220]]></CommentId>\n" +
                "    </Comments>\n" +
                "    <StatuChangeEvent>10</StatuChangeEvent>\n" +
                "  </ApprovalInfo>\n" +
                "</xml>";

        ResponseObj responseObj = new ResponseObj();
        return responseObj.ok("牛啊");

    }
}
